//
//  UserCommonManager.swift
//  bill
//
//  Created by RongJI on 2021/1/22.
//

import UIKit
import LeanCloud

class UserCommonManager: NSObject {
    static let instance = UserCommonManager()

    var phoneNum : String? {
        get {
            return (UserDefaults.standard.value(forKey: "phone") as! String)
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: "phone")
        }
    }
    
    var passWord : String?
    
    
    private override init() {
        
    }
    
    static func login(phone:String , passWord:String , _ closure: @escaping() -> Void) {
        
        _ = LCUser.logIn(username: phone, password: passWord) { result in
            switch result {
            case .success(object: let user):
                print(user)
                closure()
                UserCommonManager.instance.phoneNum = phone
                break
            case .failure(error: let error):
                print(error)
            }
        }
    }
    
    static func regist(phone:String , passWord:String , _ closure: @escaping() -> Void) {
        do {
            // 创建实例
            let user = LCUser()

            // 等同于 user.set("username", value: "Tom")
            user.username = LCString(phone)
            user.password = LCString(passWord)

            // 设置其他属性的方法跟 LCObject 一样
            try user.set("gender", value: "secret")

            _ = user.signUp { (result) in
                switch result {
                case .success:
                    closure()
                    break
                case .failure(error: let error):
                    print(error)
                }
            }
        } catch {
            print(error)
        }
    }
    
    static func loginOut(_ closure: @escaping() -> Void) {
        UserCommonManager.instance.phoneNum = ""
        
        closure()
    }
}
